// 从零开始做权限控制
import router from '@/router'
import store from '@/store'
// 引入progress插件
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// 导入动态路由表(包含所有可选的未经过滤的路由表)
import { asyncRoutes } from '@/router'
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.getters.token
  if (token) {
    // 有token
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      // 防止重复请求
      if (!store.state.user.userInfo.userId) {
        const res = await store.dispatch('user/asyncGetUserInfo')
        const menus = res.roles.menus
        const filterRoutes = asyncRoutes.filter(item => {
          return menus.includes(item.children[0].name)
        })
        store.commit('menu/setMenuList', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  // 结束
  NProgress.done()
})

